<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller\users;

use app\admin\controller\Auth;
use app\admin\controller\Paginate;
use app\common\model\Calculation;
use app\common\model\users\AccountLevelLimit;
use app\common\model\users\Users;
use app\common\model\users\Wallet;
use mall\library\wechat\chat\module\User;
use mall\utils\Date;
use mall\response\Response;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;

class Index extends Auth {

    /**
     * 用户详情列表
     * @return string|\think\response\Json
     */
    public function index(){
        if(!Request::isAjax()){ // 显示页面
            return View::fetch();
        }

        // 获取查询参数
        $params = Paginate::getSearchParams('key',[
            'has_service_charge'    => [-1,'int'],
            'balance'   => [-1,'int'],
            'username'  => ['','str'],
        ]);

        // 获取查询条件
        $where = [];

        // 收取手续费判断
        switch($params['has_service_charge']) {
            case 1:
            case 2:
                $where[] = ['has_service_charge','=',$params['has_service_charge']];
                break;
        }
        // 判断余额
        switch($params['balance']) {
            case 1:
                $where[] = ['local_balance','<=',Calculation::decimal(20)];
                break;
            case 2:
                $where[] = ['local_balance','>',Calculation::decimal(20)];
                break;
        }

        // 判断用户名搜索
        if($params['username']) {
            $where[] = ['username','like',$params['username'] . '%'];
        }

        $fields = [
            'user.id','user.username','user.local_amount','user.local_balance','user.has_service_charge','user.service_charge_rate','user.vip','user.vip_expire','user.create_time',
            'profit.profit','profit.service_charge','profit.service_charge_deducted'
        ];

        // 模型参数
        $model = (new Users())->alias('user')
            ->join('profit_statistics profit','profit.user_record=user.id','LEFT')
            ->where($where)->field($fields);
        // 获取列表数据
        $list = Paginate::getList($model);
        //返回结果
        return Response::returnArray("ok",0,$list['data'],$list['count']);
    }

    /**
     * 设置 vip 接口
     */
    public function set_vip(){
        if(!Request::isPost()) {    // 非 post 请求，直接忽视
            return Response::returnArray("操作失败，请刷新重试。",0);
        }

        /********** 验证数据 ***************/
        $data = [
            'id'    => intval(Request::post('id')),
            'status'=> intval(Request::post('status')),
        ];
        if(!in_array($data['status'],[1])) {
            return Response::returnArray("操作失败，请刷新重试。",0);
        }
        $userModel = new Users();
        if(!$details = $userModel->field(['id','vip','vip_expire','username'])->find($data['id'])) {
            return Response::returnArray("操作失败，请刷新重试。",0);
        }
        $details = $details->getData();
        if($details['vip']) {   // 判断是否为 vip
            return Response::returnArray("更新失败，请刷新重试【数据发生变化】",0);
        }
        /******** END 验证数据 *************/

        // 修改vip状态，并添加日志
        if(!$userModel->changeVipStatus($details,1)) {
            return Response::returnArray("更新失败，请刷新重试【数据发生变化】",0);
        }
        // 返回成功
        return Response::returnArray("ok");
    }

    /**
     * 修改服务费
     */
    public function set_service_charge() {
        if(!Request::isPost()) {    // 非 post 请求，直接忽视
            return Response::returnArray("操作失败，请刷新重试。",0);
        }

        /********** 验证数据 ***************/

        $data = [
            'id'    => intval(Request::post('id')),
            'rate'  => floatval(Request::post('rate')),
            'status'=> Request::post('status') == 'on'?1:2,
        ];
        if(!in_array($data['status'],[1,2])) {
            return Response::returnArray("操作失败，请刷新重试。",0);
        }


        /**
         * 判断服务费
         */
        if(bccomp($data['rate'],0,2) == -1 || bccomp($data['rate'],100,2) == 1) {
            return Response::returnArray("服务费率必须在 0-100 之间",0);
        }
        $data['rate'] = Calculation::trimZero(bcdiv($data['rate'],100,4));

        $userModel = new Users();
        if(!$details = $userModel->field(['id','has_service_charge','service_charge_rate','username'])->find($data['id'])) {
            return Response::returnArray("操作失败，请刷新重试。",0);
        }
        $details = $details->getData();
        if($details['has_service_charge'] == $data['status'] && bccomp($details['service_charge_rate'],$data['rate'],4) == 0) {   // 判断是否需要修改
            return Response::returnArray("更新失败，请刷新重试【数据发生变化】",0);
        }
        /******** END 验证数据 *************/

        // 修改服务费，并设置服务费率
        if(!$userModel->changeServiceCharge($details,$data['status'],$data['rate'])) {
            return Response::returnArray("更新失败，请刷新重试【数据发生变化】",0);
        }
        // 返回成功
        return Response::returnArray("ok");
    }


    /**
     * 后台用户充值
     */
    public function recharge() {
        if(!Request::isPost()) {    // 非 post 请求，直接忽视
            return Response::returnArray("操作失败，请刷新重试。",0);
        }

        /********** 验证数据 ***************/
        $data = [
            'id'    => intval(Request::post('id')),
            'amount'=> intval(Request::post('amount')),
            'localAmount'=> trim(Request::post('localAmount')),
        ];

        if($data['amount'] < 1 || strval($data['amount']) != trim(Request::post('amount'))) {
            return Response::returnArray("充值金额必须为大于 0 的整数。",0);
        }

        $userModel = new Users();
        if(!$details = $userModel->field(['id','local_amount','local_balance','username'])->find($data['id'])) {
            return Response::returnArray("操作失败，请刷新重试。",0);
        }
        $details = $details->getData();


        if(bccomp($details['local_amount'],$data['localAmount'],30) != 0) {   // 判断是否需要修改
            return Response::returnArray("更新失败，请刷新重试【数据发生变化】",0);
        }
        /******** END 验证数据 *************/


        try {
            Db::startTrans();

            // 修改收费状态，并添加日志
            if(!$userModel->recharge($details,$data['amount'])) {
                return Response::returnArray("更新失败，请刷新重试【数据发生变化】",0);
            }
            Db::commit();
        } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollback();
            return Response::returnArray("操作失败，请刷新重试。",0);
        }
        // 返回成功
        return Response::returnArray("ok");
    }

    /**
     * 后台提现
     */
    public function withdrawal() {
        if(!Request::isPost()) {    // 非 post 请求，直接忽视
            return Response::returnArray("操作失败，请刷新重试。",0);
        }

        /********** 验证数据 ***************/
        $data = [
            'id'    => intval(Request::post('id')),
            'amount'=> floatval(Request::post('amount')),
            'localAmount'=> trim(Request::post('localAmount')),
        ];

        if(bccomp($data['amount'],0,Users::AMOUNT_SCALE) != 1 || !preg_match('/^[0-9]+(\.[0-9]+)?$/',trim(Request::post('amount')))) {
            return Response::returnArray("提现金额必须大于0",0);
        }

        $userModel = new Users();
        if(!$details = $userModel->field(['id','local_amount','local_balance','username'])->find($data['id'])) {
            return Response::returnArray("操作失败，请刷新重试。",0);
        }
        $details = $details->getData();

        // 判断余额
        if(bccomp($data['amount'],$details['local_balance'],Users::AMOUNT_SCALE) == 1) {
            return Response::returnArray("提现金额不能大于余额",0);
        }


        if(bccomp($details['local_amount'],$data['localAmount'],30) != 0) {   // 判断是否需要修改
            return Response::returnArray("更新失败，请刷新重试【数据发生变化】",0);
        }
        /******** END 验证数据 *************/


        try {
            Db::startTrans();

            // 提现处理
            if(!$userModel->recharge($details,bcsub(0,$data['amount'],$userModel::AMOUNT_SCALE))) {
                return Response::returnArray("更新失败，请刷新重试【数据发生变化】",0);
            }
            Db::commit();
        } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollback();
            return Response::returnArray("操作失败，请刷新重试。",0);
        }
        // 返回成功
        return Response::returnArray("ok");
    }


}
